<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
		<meta content="yes" name="apple-mobile-web-app-capable" />
		<meta content="black" name="apple-mobile-web-app-status-bar-style" />
		<meta content="telephone=no" name="format-detection" />
		<meta content="email=no" name="format-detection" />
		<title>隐患上传</title>
		<link rel="stylesheet" href="../../css/hui.css" />

		<link rel="stylesheet" href="../../css/s_plus.css" />
		<link rel="stylesheet" href="../../css/base.css" />
		<link rel="stylesheet" href="../../css/layout.css" />
		<link rel="stylesheet" href="../../css/choice.css" />
		<script type="text/javascript" src="../../libs/vue.js"></script>
		<script type="text/javascript" src="../../js/jquery.1.9.1.min.js"></script>
		<script type="text/javascript" src="../../js/app/url.js"></script>
		<script type="text/javascript" src="../../libs/hui.js"></script>
		<script type="text/javascript" src="../../js/s_plus.js"></script>
		<script type="text/javascript" src="../../js/md5.js"></script>
		<script type="text/javascript" src="../../js/app/api.js"></script>
		<script type="text/javascript" src="../../js/control/swal/sweetalert.min.js"></script>
		<link rel="stylesheet" href="../../js/control/swal/sweetalert.css" />
		<script src="../../js/control/lrz.bundle.js"></script>
		<link rel="stylesheet" href="../../css/spinkit.css" />
		<script src="../../js/mui.min.js"></script>

	</head>

	<body>

		<div id="wrapper">

			<header class="f_l maxbox subhead">
				<a class="back" @click="back"><i class="iconfont">&#xe605;</i></a>
				<h1>隐患上传</h1>
			</header>
			<section class="f_l maxbox edit_list">

				<ul>

					<li>
						<b>终端编号</b>
						<p>
							<select v-model="params.termimalId" @change="getAddress">
								<option v-for="item in zdlist" :value="item.TERMIMAL_ID">{{item.TERMIMAL_CODE}}</option>
							</select>
							<!--<input class="edit_txt" v-model="params.zdId" name="" type="text" placeholder="请输入"></p>-->
					</li>
					<li>
						<b>等级：</b>
						<p>

							<select v-model="params.level">
								<option value="0">一般</option>
								<option value="1">严重</option>
							</select>
						</p>
					</li>
					<li>

						<b>类型：</b>
						<p>
							<select v-model="params.type">
								<option value="0">第三方施工</option>
								<option value="1">违章占压</option>
								<option value="2">其他</option>
							</select>
						</p>

					</li>
					<li>

						<b>影响半径 ：</b>
						<p><input class="edit_txt" v-model="params.radius" name="" type="number" placeholder="单位(m)"></p>

					</li>
					
					<li>

						<b>地址 ：</b>
						<p><input class="edit_txt" v-model="params.address"  type="text" readonly="readonly" ></p>

					</li>
					<!--<li>
      
        <b>说明：</b> <p><input class="edit_txt" v-model="params.remark"  name="" type="text" placeholder=""></p>  
     
    </li>-->
					<!--<li>
						<b>区域：</b>
						<p>

							<select v-model="params.areaId">
								<option value="ccf6eb06b1fb4b259e53636cd57a7f08">天心区</option>
								<option value="0cf7295e308e4195a394b64130404fec">宁乡县</option>
								<option value="ff0aff68a1cd4f598a03dc6bd374812e">岳麓区</option>
								<option value="5f4d95cdcdf74090b6c9a85386f1edc2">开福区</option>
								<option value="7d842a96ad8f468792eff00988639751">望城区</option>
								<option value="51b8b84ba2f84a95a7651e80206e2ed1">芙蓉区</option>
								<option value="830eaa62023c4110ac7af62800059027">长沙县</option>
								<option value="af7c16f4efb74f3d997aa0a76284516a">雨花区</option>
							</select>

						</p>
					</li>-->

				</ul>
			</section>
			<section class="f_l maxbox block_two">
				<dl>
					<dt>
      <h2>上传图片</h2>
    </dt>
					<dd class="photo_list">
						<ul>

							<li v-for="item in imgs"><img :src="item" alt="" /></li>
							<!--<li><img src="../../images/map.jpg" alt="" /></li>
        <li><img src="../../images/map.jpg" alt="" /></li>-->
							<li>
								<a id="selectImgBtn"><i class="iconfont">&#xe626;</i></a>
							</li>
							<!--<li><input class="fileControl" id="picture" type="file" accept="image/*" multiple="multiple"></li>-->

							<!--<li><input class="fileControl"  type="button" id="selectImgBtn" value="选择图片"></li>-->
						</ul>
					</dd>
				</dl>
			</section>

			<section class="f_l maxbox block_two">
				<dl>
					<dt>
      <h2>隐患描述</h2>
    </dt>
					<dd>
						<textarea class="area" v-model="params.content" name="" cols="" rows=""></textarea>
					</dd>
				</dl>
			</section>
			<section class="f_l maxbox mar_t mar_f t_c">
				<a class="btn mian_btn" @click="flag && submitData($event)">提交</a>
			</section>
			<section class="f_l maxbox mar_t mar_f t_c">
				<p>&nbsp;</p>
				<p>&nbsp;</p>

			</section>
		</div>

		<script>
			$(function() {

				function settingImgs(imgList) {

					var newUrl = imgList[0];
					if(sp.imgs != null || sp.imgs.length > 0) {
						if(sp.imgs.length < 3) {
							sp.imgs.push(newUrl);

						} else {
							sp.imgs.splice(0, 1, newUrl);

						}
					} else {
						sp.imgs.push(newUrl);
						console.log(newUrl);
					}

					//							alert(sp.imgs.splice(","));
					sp.params.url = sp.imgs.join(",");

					console.log("sp.params.url----" + sp.params.url);
					console.log("sp.imgs--" + JSON.stringify(sp.imgs));

				}

				document.getElementById('selectImgBtn').addEventListener('tap', function() {
					if(mui.os.plus) {
						var a = [{
							title: "拍照"
						}, {
							title: "从手机相册选择"
						}];
						plus.nativeUI.actionSheet({
							title: "选择照片",
							cancel: "取消",
							buttons: a
						}, function(b) { /*actionSheet 按钮点击事件*/
							switch(b.index) {
								case 0:
									break;
								case 1:
									getImage(); /*拍照*/
									break;
								case 2:
									galleryImg(); /*打开相册*/
									break;
								default:
									break;
							}
						})
					}
				}, false);

				//拍照上传
				//拍照 
				function getImage() {
					var c = plus.camera.getCamera();
					c.captureImage(function(e) {
						plus.io.resolveLocalFileSystemURL(e, function(entry) {
							var s = entry.toLocalURL() + "?version=" + new Date().getTime();
							uploadHead(s); /*上传图片*/
						}, function(e) {
							console.log("读取拍照文件错误：" + e.message);
						});
					}, function(s) {
						console.log("error" + s);
					}, {
						filename: "_doc/head.png"
					})
				}

				//从相册选图上传
				//本地相册选择 
				function galleryImg() {
					// 从相册中选择图片
					plus.gallery.pick(function(e) {
						for(var i in e.files) {
							var fileSrc = e.files[i]
							//	    	setHtml(fileSrc);
							console.log(fileSrc);
							uploadHead(fileSrc);
						}
					}, function(e) {
						console.log("取消选择图片");
					}, {
						filter: "image",
						multiple: true,
						maximum: 3,
						system: false,
						onmaxed: function() {
							plus.nativeUI.alert('最多只能选择3张图片');
						}
					});

				}

				//图片上传和压缩
				//上传头像图片 
				function uploadHead(imgPath) {
					console.log("imgPath = " + imgPath);
					//          mainImage.src = imgPath; 
					//          mainImage.style.width = "60px"; 
					//          mainImage.style.height = "60px"; 

					var image = new Image();
					image.src = imgPath;
					image.onload = function() {
						var imgData = getBase64Image(image);
						/*在这里调用上传接口*/

						hui.loading("图片上传中...");

						var username = localStorage.getItem("username");
						var sec = localStorage.getItem("sec_pwd");
						var time = apiManage.getNow();
						var key = "loginName=" + username + "&passWord=" + sec + "&time=" + time;
						var paramKey = hex_md5(key);
						var jsonParam = JSON.stringify({
							loginName: username,
							time: time,
							key: paramKey
						});

						var path = urlManager.uploadFile();
						console.log("path-------" + path);

						var form = new FormData();
						//console.log("base64----"+base64String);
						form.append("imgCode", imgData);
						$.ajax({
							type: "POST",
							url: path,
							data: form,
							contentType: false, // 注意这里应设为false
							processData: false, //false
							beforeSend: function(request) {
								request.setRequestHeader("loginName", username);
								request.setRequestHeader("time", time);
								request.setRequestHeader("sign", paramKey);
							},
							success: function(data) {
								console.log("return data-------------" + JSON.stringify(data));
								var imgList = data.pathlist;
								hui.closeLoading();
								settingImgs(imgList);
							}
						});

					}
				}
				//将图片压缩转成base64 
				function getBase64Image(img) {
					var canvas = document.createElement("canvas");
					var width = img.width;
					var height = img.height;

					var settingWH = 500; //限制宽高 
					// calculate the width and height, constraining the proportions 
					if(width > height) {
						if(width > settingWH) {
							height = Math.round(height *= settingWH / width);
							width = settingWH;
						}
					} else {
						if(height > settingWH) {
							width = Math.round(width *= settingWH / height);
							height = settingWH;
						}
					}
					canvas.width = width; /*设置新的图片的宽度*/
					canvas.height = height; /*设置新的图片的长度*/
					var ctx = canvas.getContext("2d");
					ctx.drawImage(img, 0, 0, width, height); /*绘图*/
					var dataURL = canvas.toDataURL("image/png", 0.8);
					return dataURL.replace("data:image/png;base64,", "");
				}

			});



			var sp = new Vue({
				el: "#wrapper",
				data: {
					zdlist: [],
					flag: true,
					imgs: [],
					params: {
						address:"",
						termimalId: "",
						url: "",
						"task.id": "",
						userId: "",
						type: "0", //隐患类型 0：第三方施工 1：违章占压 2：其他
						level: "0", //隐患级别 隐患等级 0：一般， 1：严重
						radius: "", //影响半径 
						remark: "",
						content: "",
						areaId: "af7c16f4efb74f3d997aa0a76284516a",
						"resTerminal.termimalId": "",
						"area.id": "af7c16f4efb74f3d997aa0a76284516a",

					}

				},
				watch: {
					zdlist(val, oldVal) { // 普通的watch监听
						 console.log("targets: "+JSON.stringify(val) +"===="+JSON.stringify(oldVal));
						
						console.log("val, oldVal-----"+ JSON.stringify(this.zdlist));
					

//						loadDetail();
					}
				},
				methods: {
					getAddress:function(){
						var tId= this.params.termimalId;
						for(var i=0;i<this.zdlist.length;i++){
							var cell = this.zdlist[i];
							if(tId ==cell.TERMIMAL_ID){
								 this.params.address = cell.belongStreet;
									console.log("找到了---" +tId +"--"+cell.TERMIMAL_ID +" address: "+this.params.address);
									break;
							}
						}
//						console.log(JSON.stringify(item));
					},
					uploadImg: function() {

					},
					back: function() {
						hui.back();
					},
					submitData: function(e) {
							
								if (!(/(^[1-9]\d*$)/.test(this.params.radius))) { 
								swal("", "影响半径只能是数字", "warning");
//		　　　　　　alert(‘输入的不是正整数’); 
		　　　　　　return; 
		　　　　}else { 
//		　　　　　　alert(‘输入的是正整数’); 
//								hui.toast("输入的是正整数");
		　　　　} 
							
						if(this.params.radius == null || this.params.radius == '') {
							console.log("console.log(this.params.radius);"+this.params.radius);
							swal("", "请填写影响半径", "warning");
							return;
						}
						
						
						
						if(this.params.content == null || this.params.content == '') {
							swal("", "请填写隐患描述", "warning");
							return;
						}

						var btn = $(e.currentTarget);
						btn.text("正在保存...");
						this.flag = false;
						upload();
					}

				}
			});

			loadZDList();
			//获取终端CODE列表
			function loadZDList() {
				var path = urlManager.terminalList();
				console.log(path);
				var username = localStorage.getItem("username");
				var sec = localStorage.getItem("sec_pwd");
				var time = apiManage.getNow();
				var key = "loginName=" + username + "&passWord=" + sec + "&time=" + time;
				console.log(key);
				var paramKey = hex_md5(key);

				var readyParam = {
					cusId: apiManage.getCompanyId(),
					status: "0"
				};
				$.ajax({
					type: "POST",
					data: readyParam,
					url: path,
					beforeSend: function(request) {
						request.setRequestHeader("loginName", username);
						request.setRequestHeader("time", time);
						request.setRequestHeader("sign", paramKey);
						//		            request.setRequestHeader("Content-Type","application/text");

					},
					success: function(result) {
						console.log("终端列表下拉框============================" + JSON.stringify(result));
						sp.zdlist = result.list;
						
						var tmp = sp.zdlist[0].TERMIMAL_ID;
						tmp = tmp.toString();
						sp.params.termimalId = tmp;
						var address = sp.zdlist[0].belongStreet;

						sp.params.address=address;

					}
				});

			}

			var userid = localStorage.getItem("userid");

			sp.params.userId = userid;

			function upload() {

				//   alert(JSON.stringify(sp.params));

				var username = localStorage.getItem("username");
				var sec = localStorage.getItem("sec_pwd");
				var time = apiManage.getNow();
				var key = "loginName=" + username + "&passWord=" + sec + "&time=" + time;
				var paramKey = hex_md5(key);
				var jsonParam = JSON.stringify({
					loginName: username,
					time: time,
					key: paramKey
				});

				var path = urlManager.uploadCheckTrouble();

				sp.params["area.id"] = sp.params.areaId;
				sp.params["resTerminal.termimalId"] = sp.params.termimalId;

				console.log("path ------" + path);
				console.log("参数==========" + JSON.stringify(sp.params));
				hui.loading("");
				$.ajax({
					type: "POST",
					url: path,
					data: sp.params,
					beforeSend: function(request) {
						request.setRequestHeader("loginName", username);
						request.setRequestHeader("time", time);
						request.setRequestHeader("sign", paramKey);
						//		            request.setRequestHeader("Content-Type","application/text");

					},
					success: function(result) {
						hui.closeLoading();

						console.log("隐患上传:" + JSON.stringify(result));

						var riskListUrl = "risk.html?time=" + apiManage.getNow();

						if(result.error_code == null || result.error_code == '-1') {
							swal({  
									title: "提交失败",
									  text: result.error_msg,
									  type: "error",
									  showCancelButton: false,
									  confirmButtonColor: "#DD6B55",
									  confirmButtonText: "确认",
									  cancelButtonText: "取消",
									  closeOnConfirm: true,
									  closeOnCancel: false
								},
								function(isConfirm) {  
									if(isConfirm) {
										hui.open(riskListUrl, {}, true, {});  
									} else {  }
								});
						} else {

							swal({  
									title: "保存成功",
									  text: result.error_msg,
									  type: "success",
									  showCancelButton: false,
									  confirmButtonColor: "#DD6B55",
									  confirmButtonText: "确认",
									  cancelButtonText: "取消",
									  closeOnConfirm: true,
									  closeOnCancel: false
								},
								function(isConfirm) {  
									if(isConfirm) {
										hui.open(riskListUrl, {}, true, {});  
									} else {  }
								});

						}

					}

				});

			}
			
			
			
				
			function loadDetail(){
					var cell=localStorage.getItem("cell");
					
					var param = JSON.parse(cell);
					console.log("params--"+cell);
					var username=	localStorage.getItem("username");
					var sec= localStorage.getItem("sec_pwd");
				  	var time = apiManage.getNow();
				  	var key = "loginName="+username+"&passWord="+sec+"&time="+time;
				  	var paramKey=hex_md5(key);
				  	var jsonParam = JSON.stringify({loginName:username,time:time,key:paramKey});
				     console.log("jsonParam:  "+jsonParam);
				     
				     var zdId = sp.params.termimalId;
				     				     console.log("终端详情：----"+zdId);

						var path = urlManager.terminalDetail()+"?terminalCode="+zdId;
						
						console.log("path:  "+path);
							hui.loading("");
								 $.ajax({
						         type: "GET",
						         url: path,
						         beforeSend: function(request) {
						            request.setRequestHeader("loginName",username);
						            request.setRequestHeader("time",time);
						            request.setRequestHeader("sign",paramKey);
						            request.setRequestHeader("Content-Type","application/text");
						
						         },
						         success: function(result) {
						         	hui.closeLoading();
						          	console.log("终端详情:"+JSON.stringify(result));
//						          	
//						          	sp.zd=result;
//						          	console.log("result.jgId----"+JSON.stringify(result.jgId));
//						          	sp.jg=result.jgId;
////									sp.risk=result;
////									sp.lists=result.zds;
//									if(result.imgUrl!=null){
//										sp.urls = result.imgUrl.split(",");
//									}
				
										}		 
						             
						         
						     });
				  
					
					
				}
			
		</script>

	

	</body>

</html>